/*
 *所有关于Process类的业务代码应在此处编写
*可使用repository.调用常用方法，获取EF/Dapper等信息
*如果需要事务请使用repository.DbContextBeginTransaction
*也可使用DBServerProvider.手动获取数据库相关信息
*用户信息、权限、角色等使用UserContext.Current操作
*ProcessService对增、删、改查、导入、导出、审核业务代码扩展参照ServiceFunFilter
*/
using VOL.Core.BaseProvider;
using VOL.Core.Extensions.AutofacManager;
using VOL.Entity.DomainModels;
using System.Linq;
using VOL.Core.Utilities;
using System.Linq.Expressions;
using VOL.Core.Extensions;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.AspNetCore.Http;
using VOL.Domain.IRepositories;
using System.Threading.Tasks;
using VOL.Domain.Dto;
using VOL.Domain.Infrastructure;
using System.Diagnostics;
using System.Collections.Generic;

namespace VOL.Domain.Services
{
    public partial class ProcessService
    {
        private readonly IHttpContextAccessor _httpContextAccessor;
        private readonly IBaseRepository<Entity.DomainModels.Process> _processbaseRepository;
        private readonly IBaseRepository<CompositionProcess> _compositionProcessRepository;
        private readonly IProcessRepository _repository;//访问数据库

        [ActivatorUtilitiesConstructor]
        public ProcessService(
            IProcessRepository dbRepository,
            IHttpContextAccessor httpContextAccessor,
            IBaseRepository<Entity.DomainModels.Process> baseRepository,
            IBaseRepository<CompositionProcess> compositionProcessRepository
            )
        : base(dbRepository)
        {
            _httpContextAccessor = httpContextAccessor;
            this._processbaseRepository = baseRepository;
            this._compositionProcessRepository = compositionProcessRepository;
            _repository = dbRepository;
            //多租户会用到这init代码，其他情况可以不用
            //base.Init(dbRepository);
        }
        
        /// <summary>
        /// 分页查询工艺路线
        /// </summary>
        /// <param name="searchDto">查询参数</param>
        /// <returns>查询结果</returns>
        public async Task<WebResponseContent> GetProcessPageData(ProcessSearchDto searchDto)
        {
            var response = new WebResponseContent();
            var query = _repository.FindAsIQueryable(x => true);

            if (!string.IsNullOrEmpty(searchDto.ProcessCode))
                query = query.Where(x => x.ProcessCode.Contains(searchDto.ProcessCode));
            if (!string.IsNullOrEmpty(searchDto.ProcessName))
                query = query.Where(x => x.ProcessName.Contains(searchDto.ProcessName));
            if (searchDto.Status != null)
                query = query.Where(x => x.Status == searchDto.Status);

            // 排序
            var orderBy = new Dictionary<string, VOL.Core.Enums.QueryOrderBy> { { "Id", VOL.Core.Enums.QueryOrderBy.Desc } };
            int rowCount = 0;
            var result = _repository.IQueryablePage(query, searchDto.Page, searchDto.PageSize, out rowCount, orderBy);

            response.Data = new { rows = result, total = rowCount };
            response.Status = true;
            return response;
        }

        /// <summary>
        /// 创建工艺路线
        /// </summary>
        /// <param name="process">工艺路线实体</param>
        /// <returns>创建结果</returns>
        public async Task<WebResponseContent> AddProcess(Entity.DomainModels.Process process)
        {
            WebResponseContent response = new WebResponseContent();

          
            try
            {
                // 添加记录
                _repository.Add(process, true);
                response.Status = true;
                response.Data = process;
                response.Message = "创建成功";
                return response;
            }
            catch (Exception ex)
            {
                return response.Error($"创建失败：{ex.Message}");
            }
        }

        /// <summary>
        /// 修改工艺路线
        /// </summary>
        /// <param name="process">工艺路线实体</param>
        /// <returns>修改结果</returns>
        public async Task<WebResponseContent> UpdateProcess(Entity.DomainModels.Process process)
        {
            WebResponseContent response = new WebResponseContent();

            // 检查ID是否存在
            var existProcess = await _repository.FindFirstAsync(p => p.Id == process.Id);
            if (existProcess == null)
            {
                return response.Error("修改失败：未找到指定的工艺路线记录");
            }

            // 检查编号是否已被其他记录使用
            if (await _repository.ExistsAsync(p => p.ProcessCode == process.ProcessCode && p.Id != process.Id))
            {
                return response.Error($"工艺路线编号[{process.ProcessCode}]已被其他记录使用");
            }

            try
            {
                // 更新记录
                _repository.Update(process, true);
                response.Status = true;
                response.Data = process;
                response.Message = "修改成功";
                return response;
            }
            catch (Exception ex)
            {
                return response.Error($"修改失败：{ex.Message}");
            }
        }

        /// <summary>
        /// 批量删除工艺路线
        /// </summary>
        /// <param name="ids">工艺路线ID数组</param>
        /// <returns>删除结果</returns>
        public async Task<WebResponseContent> BatchDeleteProcess(int[] ids)
        {
            WebResponseContent response = new WebResponseContent();
            try
            {
                // 使用DeleteAsync方法删除指定ID的记录
                int result = await _processbaseRepository.DeleteAsync(x => ids.Contains(x.Id));
                
                if (result > 0)
                {
                    response.Status = true;
                    response.Message = $"成功删除{result}条记录";
                }
                else
                {
                    response.Status = false;
                    response.Message = "未找到要删除的记录";
                }
                
                return response;
            }
            catch (Exception ex)
            {
                return response.Error($"删除失败：{ex.Message}");
            }
        }

        /// <summary>
        /// 分页查询组成工序
        /// </summary>
        /// <param name="searchDto">查询条件和分页参数</param>
        /// <returns>分页数据</returns>
        public async Task<WebResponseContent> GetCompositionProcessPageData(CompositionProcessSearchDto searchDto)
        {
            var response = new WebResponseContent();
            var query = _compositionProcessRepository.GetAll();

            // 应用查询条件
            if (!string.IsNullOrEmpty(searchDto.Code))
                query = query.Where(x => x.Code.Contains(searchDto.Code));
            if (!string.IsNullOrEmpty(searchDto.ProcessCode))
                query = query.Where(x => x.ProcessCode.Contains(searchDto.ProcessCode));
            if (!string.IsNullOrEmpty(searchDto.ProcessName))
                query = query.Where(x => x.ProcessName.Contains(searchDto.ProcessName));
            if (!string.IsNullOrEmpty(searchDto.NextProcess))
                query = query.Where(x => x.NextProcess.Contains(searchDto.NextProcess));

            // 设置排序
            query = query.OrderBy(x => x.Id);
            
            // 执行分页查询
            int rowCount = await query.CountAsync();
            var result = await query.Skip((searchDto.Page - 1) * searchDto.PageSize)
                                  .Take(searchDto.PageSize)
                                  .ToListAsync();

            response.Data = new { rows = result, total = rowCount };
            response.Status = true;
            
            return response;
        }

        /// <summary>
        /// 添加组成工序
        /// </summary>
        /// <param name="compositionProcess">组成工序实体</param>
        /// <returns>添加结果</returns>
        public async Task<WebResponseContent> AddCompositionProcess(CompositionProcess compositionProcess)
        {
            WebResponseContent response = new WebResponseContent();

           
            try
            {
                // 添加记录
                await _compositionProcessRepository.Add(compositionProcess);
                response.Status = true;
                response.Data = compositionProcess;
                response.Message = "创建成功";
                return response;
            }
            catch (Exception ex)
            {
                return response.Error($"创建失败：{ex.Message}");
            }
        }

        /// <summary>
        /// 修改组成工序
        /// </summary>
        /// <param name="compositionProcess">组成工序实体</param>
        /// <returns>修改结果</returns>
        public async Task<WebResponseContent> UpdateCompositionProcess(CompositionProcess compositionProcess)
        {
            WebResponseContent response = new WebResponseContent();

            try
            {
                // 更新记录
                await _compositionProcessRepository.Update(compositionProcess);
                response.Status = true;
                response.Data = compositionProcess;
                response.Message = "修改成功";
                return response;
            }
            catch (Exception ex)
            {
                return response.Error($"修改失败：{ex.Message}");
            }
        }

        /// <summary>
        /// 批量删除组成工序
        /// </summary>
        /// <param name="ids">组成工序ID数组</param>
        /// <returns>删除结果</returns>
        public async Task<WebResponseContent> BatchDeleteCompositionProcess(int[] ids)
        {
            WebResponseContent response = new WebResponseContent();
            
            if (ids == null || ids.Length == 0)
            {
                return response.Error("请选择要删除的记录");
            }

            try
            {
                // 使用DeleteAsync方法删除指定ID的记录
                int result = await _compositionProcessRepository.DeleteAsync(x => ids.Contains(x.Id));
                
                if (result > 0)
                {
                    response.Status = true;
                    response.Message = $"成功删除{result}条记录";
                }
                else
                {
                    response.Status = false;
                    response.Message = "未找到要删除的记录";
                }
                
                return response;
            }
            catch (Exception ex)
            {
                return response.Error($"删除失败：{ex.Message}");
            }
        }
    }
}
